;(function () {
  new Vue({
    el: '#unit-floor',
    data: {
      unitId: hlUrlUtil.GetQueryString('fyid'),
			projectId: hlUrlUtil.GetQueryString('projectId'),
      permissions: JSON.parse(window.localStorage.getItem('permissions')),
      basisFlag: false,
      standard: false,
      picture: false,
      active: 'Y',
      cmrType: [{name:'是', code:'Y'}, {name:'否', code: 'N'}],
      unitData: {
        unitPositionImg: null,
        unitPlainImg: [],
        consImgs: [],
        innerImgs: [],
        facilitys: [],
        sellPriceUnits:''
      },
      facilitysData: [],
      decoration: [],
      orientationData: [],
      uploadImg: null,
      unitMsg: false,
      unitNav: [],

      unitCurrent: '',
      contractFile: [],
			//附加信息
			isDefaultArr: [{name: '是', code: 'Y'}, {name: '否', code: 'N'}],
			zcestatetypeArr: [],
			zcpropertytypeArr: [],
			zcleaseholderorgtypeArr: [],
			existingFlag: 'N',
			existingId: '',
			buildAreage: '',
			inAreage: '',
			leaseAreage: '',
			adminUnit: '',
			adminUnit0: '',
			useUnit: '',
			useSoUnit: '',
			useNumber: '',
			endTime: '',
			beginTime: '',
			unitConact: '',
			unitPhone: '',
			ztcAreage: '',
			zhUnit: '',
			term: '',
			fallInto: '',
			approval: '',
			inMoney: '',
			outMoney: '',
			memo: '',
			publicRental: '#', //是否公开招租
			zcestatetype: '#', //业态
			zcpropertytype: '#', //物业状态
      zcleaseholderorgtype: '#', //使用单位性质
      progress:'',
      permissions:  JSON.parse(window.localStorage.getItem('permissions')) ,
			debishadiao: []
    },
    filters: {
      tofixed2: function (n) {
        var num = Number(n) ? n : '0'
        return Number(num).toFixed(2)
      },
      businessTypev: function (str) {
        let result;
        switch (str) {
          case 'BU':
            result = '普通单元'
            break;
          case 'ST':
            result = '停车场'
            break;
          case 'WP':
            result = '联合办公'
            break;
          default:
            result = '--'
        }
        return result
      },
      facilitysv: function (str) {
        return hlCodeConvert.facilitys(str)
      },      
      orientationv: function (str) {
        if (!str) return '--';
        return hlCodeConvert.orientation(str)
      }
    },
		computed: {
			typeval () {
				let val;
				this.decoration.map(item => {
					if (this.unitData.decorationType == item.code) {
						val = item.memo
					}
				})
				return val
			},
			decorationStageVal () {
				let val;
				this.debishadiao.map(item => {
					if (this.unitData.decorationStage == item.dictCode) {
						val = item.dictName
					}
				})
				return val
			}
		},
    methods: {
			//资源规划-项目单元信息业态字典
			zcestatetypeDt () {
				hlhttp.get({
					url: 'configure/dict',
					data: {	module_code: 'ZICH', config_name: 'ZC_ESTATE_TYPE'},
					success: (data) => {
						this.zcestatetypeArr = data;
					}
				})
			},
			//资源规划-项目单元信息物业状态字典
			zcpropertytypeDt () {
				hlhttp.get({
					url: 'configure/dict',
					data: {	module_code: 'ZICH', config_name: 'ZC_PROPERTY_TYPE'},
					success: (data) => {
						this.zcpropertytypeArr = data;
					}
				})
			},
			//资源规划-项目单元信息使用单位性质字典
			zcleaseholderorgtypeDt () {
				hlhttp.get({
					url: 'configure/dict',
					data: {	module_code: 'ZICH', config_name: 'ZC_LEASEHOLDER_ORG_TYPE'},
					success: (data) => {
						this.zcleaseholderorgtypeArr = data;
					}
				})
			},


      valxy: function (item, name) {
        if (item == 0) return;
        if (!Number(item)) {
          hl.toast('请填写数字')
          this.unitData[name] = '0.00';
          return
        }
        if (item < 0) {
          hl.toast('数字不能为负数')
          this.unitData[name] = '0.00';
          return
        }
        this.unitData[name] = Number(this.unitData[name]).toFixed(2)
      },
      setcmrDataAtType: function (code) {
        this.active = code
        this.unitData.streetType = code;
      },
      // 编辑基础信息
      basisInfoo: function () {
        this.basisFlag = !this.basisFlag;
        if (!this.active) {
          this.active = 'Y'
        }
      },
      //获取单元信息
      getUnitData: function () {
        var self = this;
        hlhttp.get({
          url: 'unit/info',
          data: {unit_id: hlUrlUtil.GetQueryString('fyid')},
          success: function (res) {
            if (!res.unitPositionImg) {
              res.unitPositionImg = '';
            }
            if (!res.unitPlainImg) {
              res.unitPlainImg = [];
            }else{
              res.unitPlainImg = res.unitPlainImg.split(',')
            }
            if (!res.memo) {
              res.memo = '';
            }
            self.contractFile = []
            if (res.attachmentNames) {
              var attname = res.attachmentNames.split(',')
              var atturl = res.attachmentUrls.split(',')
              for (var i = 0; i < attname.length; i++) {
                self.contractFile.push({name:attname[i],url:atturl[i]})
              }
            }

            res.sellPrice = res.sellPrice ? Number(res.sellPrice).toFixed(2) : '0.00';
            res.sellPriceUnits = res.sellPriceUnits;
            res.unitAcreage = res.unitAcreage ? Number(res.unitAcreage).toFixed(2) : '0.00';
            res.consAcreage = res.consAcreage ? Number(res.consAcreage).toFixed(2) : '0.00';
            res.innerAcreage = res.innerAcreage ? Number(res.innerAcreage).toFixed(2) : '0.00';
            res.houseStyle = res.houseStyle || ''
            res.streetAddress =  res.streetAddress || ''
            self.unitData = res;
            self.active = res.streetType;
            self.facilityTypes()
          }
        })
      },
      //获取基础设施类型列表
      facilityTypes: function () {
        var self = this;
        hlhttp.get({
          url: 'configure/facility/dict',
          success: function (res) {
            for (var i = 0; i < res.length; i++) {
              res[i].flag = false;
              if (self.unitData.facilitys.indexOf(res[i].dictCode) > -1) {
                res[i].flag = true;
              }
            }
            self.facilitysData = res;
          }
        })
      },
      //编辑配套
      flagIs: function () {
        for (var i = 0; i < this.facilitysData.length; i++) {
          this.facilitysData[i].flag = true;
        }
        this.standard = !this.standard;
      },
      //获取装修水平类型列表
      getDecorationtypes: function () {
        var self = this;
        hlhttp.get({
          url: 'unit/decoration_types',
          success: function (res) {
            self.decoration = res;
          }
        })
      },
      //获取朝向类型列表
      getOrientationtypes: function () {
        var self = this;
        hlhttp.get({
          url: 'unit/orientation_types',
          success: function (res) {
            self.orientationData = res;
          }
        })
      },
      // 编辑单元信息
      putbaseinfo: function () {
        if(!this.unitData.sellPriceUnits){
          hl.toast('请输入价格单位');
          return
        }
        var self = this;
        hlhttp.put({
          url: 'unit/base_info',
          data: {
						decoration_stage: self.unitData.decorationStage, 
            sell_price: self.unitData.sellPrice,     //显示价格
            sell_price_units: self.unitData.sellPriceUnits,     //显示价格单位
            cons_acreage: self.unitData.consAcreage,     //建筑面积
            inner_acreage: self.unitData.innerAcreage,     //套内面积
            house_style:self.unitData.houseStyle,   //户型
            street_address:self.unitData.streetAddress, // 行政街道
            decoration_type: self.unitData.decorationType || 'ET',     //装修水平
            orientation_type: self.unitData.orientationType || 'ET',     //朝向
            street_type: self.active || 'Y',     //临街
            unit_id: self.unitId,    //单元ID
          },
          success: function () {
            hl.toast('编辑成功')
						self.basisFlag = false;
						self.getUnitData()						
            
            if (!self.unitData.decorationType) {
              self.unitData.decorationType = 'ET'
            }
            if (!self.unitData.orientationType) {
              self.unitData.orientationType = 'ET'
            }
            if (!self.unitData.streetType) {
              self.unitData.streetType = 'Y'
            }
          }
        })
      },
      //编辑单元设施
      putfacilitys: function () {
        var self = this;
        hlhttp.put({
          url: 'unit/facilitys',
          data: {
            facilitys: self.unitData.facilitys.toString() || '#',
            unit_id: self.unitId    //单元ID
          },
          success: function () {
            hl.toast('编辑成功')
            self.standard = false;
            self.getUnitData()
          }
        })
      },
      //编辑单元图片
      putimgs: function () {
        var self = this;
        hlhttp.put({
          url: 'unit/imgs',
          data: {
            unit_position_img: self.unitData.unitPositionImg || '#',
            unit_plain_img: self.unitData.unitPlainImg + '' || '#',
            cons_imgs: self.unitData.consImgs.toString() || '#',
            inner_imgs: self.unitData.innerImgs.toString() || '#',
            unit_id: self.unitId    //单元ID
          },
          success: function () {
            hl.toast('编辑成功')
            self.picture = false;
          }
        })
      },
      //编辑单元备注
      putmemo: function () {
        var self = this;
        hlhttp.post({
          url: 'unit/memo',
          data: {
            memo: self.unitData.memo || '#',
            unit_id: self.unitId    //单元ID
          },
          success: function () {
            hl.toast('编辑成功')
            self.unitMsg = false;
          }
        })
      },
      //设置设施
      setfacilitys: function (code, ix) {
        if (!this.standard) return;
        var kcode = this.unitData.facilitys;
        if (!(kcode.indexOf(code) > -1)) {
          this.unitData.facilitys.push(code)
          return
        }
        for (var i = 0; i < kcode.length; i++) {
          if (kcode[i] == code) {
            this.unitData.facilitys.splice(i, 1)
          }
        }
      },
      uploadImgs: function (n) {
        this.uploadImg = n;
        $('.js-trigger-upload').trigger('click')
      },
      delPic: function (n, i) {
        if (n == 0) {
          this.unitData.unitPositionImg = null;
        }
        if (n == 1) {
          this.unitData.unitPlainImg.splice(i, 1);
        }
        if (n == 2) {
          this.unitData.consImgs.splice(i, 1)
        }
        if (n == 3) {
          this.unitData.innerImgs.splice(i, 1)
        }
      },
      //大图浏览
      getBigPic: function (img, i, s) {
        if (s == 'o') {
          var temp = img ? img.split(',') : null;
          $.imageShow(temp, i)
          return
        }
        $.imageShow(img, i)
      },
      uploadFile: function () {
        if(this.progress){
          hl.toast('文件尚未上传完成')
          return
      }
        $('.js-trigger-upload1').trigger('click')
      },
       //***  相关文件
       previewImage: function(url) {
        var imageExt = ['jpg', 'jpeg', 'png', 'JPG', 'JPEG', 'PNG'];
        var pdfExt = ['pdf', 'PDF'];
        var officeExt = ['docx','doc','xlsx','xls','xlt']
        var imageFlag = false;
        var pdfFlag = false;
        var officeFlag = false;

        imageExt.forEach((e, i) => {
          if (url.indexOf(e) !== -1) imageFlag = true;
        })

        if (imageFlag) {
          $.imageShow([url])
          return
        }
        pdfExt.forEach((e, i) => {
          if (url.indexOf(e) !== -1) pdfFlag = true;
        })
        if (pdfFlag) {
          $.previewPDF(url)
          return
        }

        officeExt.forEach((e, i) => {
          if (url.indexOf(e) !== -1) officeFlag = true
        })
        if (officeFlag) {
          $.previewOffice(url)
          return
        }
        hl.toast('暂不支持该格式')
      },
      // 删除文件
      deleteFile: function(val, i) {
        var self = this;
        hlhttp.delete({
          url: 'unit_attachment?unit_id=' + self.unitId + '&attachment_url=' + val,
          success: function() {
            hl.toast('删除成功')
            self.contractFile.splice(i, 1)
          }
        })
      },
			//导航切换
			menuTab (item) {
				this.unitCurrent = item;
				if (item == '附加信息') {this.AddInfoDt()}
			},
			//附加信息
			submitAddInfo () {
				let data = {
					buildAreage: this.buildAreage,
					inAreage: this.inAreage,
					leaseAreage: this.leaseAreage,
					adminUnit: this.adminUnit,
					adminUnit0: this.adminUnit0,
					useUnit: this.useUnit,
					useSoUnit: this.useSoUnit,
					useNumber: this.useNumber,
					endTime: this.endTime,
					beginTime: this.beginTime,
					unitConact: this.unitConact,
					unitPhone: this.unitPhone,
					ztcAreage: this.ztcAreage,
					zhUnit: this.zhUnit,
					term: this.term,
					fallInto: this.fallInto,
					approval: this.approval,
					inMoney: this.inMoney,
					outMoney: this.outMoney,
					memo: this.memo,
					publicRental: this.publicRental,
					zcestatetype: this.zcestatetype,
					zcpropertytype: this.zcpropertytype,
					zcleaseholderorgtype: this.zcleaseholderorgtype
				}
			},
			//获取附加信息
			AddInfoDt () {
				hlhttp.get({
					url: 'project/unit_extra_info',
					data: {project_id: this.projectId, unit_id: this.unitId},
					success: (data) => {
						this.existingFlag = data.existingFlag;
						if (data.existingFlag == 'N') return;
						this.existingId = data.extInfo.id;
						this.buildAreage = data.extInfo.coveredAcreage;
						this.inAreage = data.extInfo.insideAcreage;
						this.leaseAreage = data.extInfo.rentAcreage;
						this.zcestatetype = data.extInfo.estateTypeCode;
						this.$refs.yt.innerHTML = data.extInfo.estateType ? data.extInfo.estateType : '请选择';
						this.adminUnit = data.extInfo.manageDept;
						this.adminUnit0 = data.extInfo.manageDeptAdmin;
						this.zcpropertytype = data.extInfo.propertyTypeCode;
						this.$refs.wyzt.innerHTML = data.extInfo.propertyType ? data.extInfo.propertyType : '请选择';
						this.useUnit = data.extInfo.leaseholderType;
						this.useSoUnit = data.extInfo.leaseholderOrg;
						this.zcleaseholderorgtype = data.extInfo.leaseholderOrgCateCode;
						this.$refs.dwxz.innerHTML = data.extInfo.leaseholderOrgCate ? data.extInfo.leaseholderOrgCate : '请选择';
						this.useNumber = data.extInfo.leaseholderAmount;
						this.endTime = hlDateUtil.formatUTCDate(data.extInfo.rentEndTime, 'yyyy-MM-dd');
						this.beginTime = hlDateUtil.formatUTCDate(data.extInfo.rentStartTime, 'yyyy-MM-dd');
						this.unitConact = data.extInfo.leaseholderOrgContact;
						this.unitPhone = data.extInfo.leaseholderOrgPhone;
						this.ztcAreage = data.extInfo.disposalAreaAcreage;
						this.zhUnit = data.extInfo.disposalOrgName;
						this.publicRental = data.extInfo.publicRentalFlag ? data.extInfo.publicRentalFlag : '#';
						this.$refs.zhaozu.innerHTML = data.extInfo.publicRentalFlag ? data.extInfo.publicRentalFlag == 'Y' ? '是' : '否' : '请选择';
						this.term = data.extInfo.disposalTerm;
						this.fallInto = data.extInfo.appointmentRentAmount;
						this.approval = data.extInfo.approvalUnit;
						this.inMoney = data.extInfo.disposalIncome;
						this.outMoney = data.extInfo.treasuryAmount;
						this.memo = data.extInfo.memo;
					}
				})
			},
			//参数
			addinionalData () {
				let data = {
					covered_acreage: this.buildAreage ? this.buildAreage + '' : '#',
					inside_acreage: this.inAreage ? this.inAreage + '' : '#',
					rent_acreage: this.leaseAreage ? this.leaseAreage + '' : '#',
					estate_type_code: this.zcestatetype || '#',
					estate_type: this.$refs.yt.innerHTML == '请选择' ? '#' : this.$refs.yt.innerHTML,
					manage_dept: this.adminUnit || '#',
					manage_dept_admin: this.adminUnit0 || '#',
					property_type_code: this.zcpropertytype || '#',
					property_type: this.$refs.wyzt.innerHTML == '请选择' ? '#' : this.$refs.wyzt.innerHTML,
					leaseholder_type_code: '#',
					leaseholder_type: this.useUnit || '#',
					leaseholder_org: this.useSoUnit || '#',
					leaseholder_org_cate_code: this.zcleaseholderorgtype || '#',
					leaseholder_org_cate: this.$refs.dwxz.innerHTML == '请选择' ? '#' : this.$refs.dwxz.innerHTML,
					leaseholder_amount: this.useNumber || '#',
					rent_start_time: this.beginTime || '#',
					rent_end_time: this.endTime || '#',
					leaseholder_org_contact: this.unitConact || '#',
					leaseholder_org_phone: this.unitPhone || '#',
					disposal_area_acreage: this.ztcAreage ? this.ztcAreage + '' : '#',
					disposal_org_name: this.zhUnit || '#',
					public_rental_flag: this.publicRental || '#',
					disposal_term: this.term || '#',
					appointment_rent_amount: this.fallInto + '' || '#',
					approval_unit: this.approval || '#',
					disposal_income: this.inMoney ? this.inMoney + '' : '#',
					treasury_amount: this.outMoney ? this.outMoney + '' : '#',
					memo: this.memo || '#'
				}
				return data;
			},
			//新增
			additional () {
				hlhttp.post({
					url: 'project/unit_extra_info',
					data: {
						project_id: this.projectId + '',
						unit_id: this.unitId + '',
						ext_info: JSON.stringify(this.addinionalData())
					},
					success: (data) => {
						this.existingId = data.extInfoId;
						this.existingFlag = 'Y';
						hl.toast('保存成功')
					}
				})
			},
			//编辑
			editAdditional () {
				let data = {id: this.existingId}
				let obj = Object.assign({},this.addinionalData(),data)
				hlhttp.put({
					url: 'project/unit_extra_info',
					data: {
						project_id: this.projectId + '',
						unit_id: this.unitId + '',
						ext_info: JSON.stringify(obj)
					},
					success: (data) => {
						this.existingId = data.extInfoId
						hl.toast('保存成功')
					}
				})
			},
			//判断新增编辑
			addEditDetail () {
				if (this.existingFlag == 'Y') {this.editAdditional()}
				if (this.existingFlag == 'N') {this.additional()}
			},
			getDebishadiaoData () {
			  hlhttp.get({
			    url: 'configure/dict',
			    data: {module_code: 'ZUKN', config_name: 'ZK_DECORATION_STAGE'},
			    success: res => {			     
			      this.debishadiao = res;
			    }
			  })
			}
    },
    created(){
      let list = JSON.parse(window.localStorage.getItem('permissions'))
      let arr = [{name: '单元详情', code: 'c266'}, {name: '附加信息', code: 'c267'}, {name: '相关文件', code: 'c268'}]
      arr.map(item => {
        if (list.indexOf(item.code) > -1) {
          this.unitNav.push(item.name)
        }
      })
      if(this.unitNav.length){
        this.unitCurrent = this.unitNav[0]
      }
    },
    mounted: function () {
			this.getDebishadiaoData()
      this.getDecorationtypes()
      this.getOrientationtypes()
      this.getUnitData()
			this.zcestatetypeDt()
			this.zcpropertytypeDt()
			this.zcleaseholderorgtypeDt()
      hlSelectUi()
      var self = this;

      uploader('.bill-settlement', '.js-trigger-upload', uploadUrl, function (src) {
        if (self.uploadImg == 0) {
          self.unitData.unitPositionImg = src.json.url;
        }
        if (self.uploadImg == 1) {
          self.unitData.unitPlainImg.push(src.json.url);
        }
        if (self.uploadImg == 2) {
          self.unitData.consImgs.push(src.json.url);
        }
        if (self.uploadImg == 3) {
          self.unitData.innerImgs.push(src.json.url);
        }
      })
      var that = this
      fileUpload('.js-trigger-upload1', uploadUrl, function (res) {
        that.progress = ''
        hlhttp.post({
          url: 'unit_attachment',
          data: {
            unit_id: self.unitId,
            attachment_names: res.json.name,
            attachment_url: res.json.url
          },
          success: function () {
            hl.toast('上传成功')
            self.contractFile.push(res.json)
          }
        })

      },function(val){
        that.progress = parseInt((val.loaded/val.total)*100) + '%'
      })
    }
  })
} ())
